package vns.client.view;

import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.types.Assertions.EnabledAssertion;

import vns.client.helper.Helper;
import vns.client.presenter.RuleParamPresenter;
import vns.shared.RuleParamDTO;
import vns.shared.RuleSetDTO;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FlexTable;

public class RuleParamUI extends Composite implements
		RuleParamPresenter.Display {

	private List<String> listStringColumn = new ArrayList<String>();
	private static RuleParamUIUiBinder uiBinder = GWT
			.create(RuleParamUIUiBinder.class);
	private static int rowSelectedID = -1;
	private static int rowEditingID = -1;

	private final RuleSetDTO currentRuleSetDTO;
	private List<RuleParamDTO> listRow = new ArrayList<RuleParamDTO>();

	@UiField
	FlexTable flexTable;
	@UiField
	Button btAdd;
	@UiField
	Button btDel;
	@UiField
	Button btUpdate;
	@UiField
	HorizontalPanel horPanelParamControl;

	interface RuleParamUIUiBinder extends UiBinder<Widget, RuleParamUI> {
	}

	/*
	 * Constructor
	 */
	public RuleParamUI(RuleSetDTO currentRuleSetDTO) {
		this.currentRuleSetDTO = currentRuleSetDTO;
		initWidget(uiBinder.createAndBindUi(this));
		bind();
	}

	private void bind() {
		/*
		 * Tên các cột
		 */
		listStringColumn.add(""); // order
		listStringColumn.add("Tên đối số"); // var
		listStringColumn.add("Đặc tả"); // property path

		flexTable.setBorderWidth(1);
		flexTable.setCellPadding(2);
		flexTable.setCellSpacing(0);

		/*
		 * FlexTable Even
		 */
		flexTable.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getClickedRow(event);

			}
		});

	}

	/***************************************************************************/
	public void renderEditingRow() {
		if (rowEditingID > 0) {
			HTMLTable.RowFormatter rf = flexTable.getRowFormatter();
			rf.addStyleName(rowEditingID, "vnsEditingRow");
		}
	}

	public void unrenderEditingRow() {
		if (rowEditingID > 0) {
			HTMLTable.RowFormatter rf = flexTable.getRowFormatter();
			rf.removeStyleName(rowEditingID, "vnsEditingRow");
		}
	}

	public void renderClickedRow() {
		if (rowSelectedID > 0) {
			HTMLTable.RowFormatter rf = flexTable.getRowFormatter();
			rf.addStyleName(rowSelectedID, "vnsClickedRow");
		}
	}

	public void unrenderClickedRow() {
		if (rowSelectedID > 0) {
			HTMLTable.RowFormatter rf = flexTable.getRowFormatter();
			rf.removeStyleName(rowSelectedID, "vnsClickedRow");
		}
	}

	public int getClickedRow(ClickEvent event) {
		int selectedRow = -1;
		HTMLTable.Cell cell = flexTable.getCellForEvent(event);

		if (cell != null) {
			if (cell.getCellIndex() >= 0) {
				selectedRow = cell.getRowIndex();
			}
		}
		swapClickedRow(selectedRow, cell.getCellIndex());
		return selectedRow;
	}

	private void swapClickedRow(int rowNow, int cellindex) {
		if (rowNow != rowSelectedID && rowNow > 0 && rowNow != rowEditingID) {
			unrenderClickedRow();
			setRowEnable(rowSelectedID, false);
			rowSelectedID = rowNow;

			renderClickedRow();
			setRowEnable(rowSelectedID, true);
		} else if (rowNow == rowSelectedID && rowNow > 0
				&& rowNow != rowEditingID) {
			if (cellindex == 0) {
				unrenderClickedRow();
				setRowEnable(rowSelectedID, false);
				rowSelectedID = -1;
			}
		} else if (rowNow == -1) {
			unrenderClickedRow();
			setRowEnable(rowSelectedID, false);
			rowSelectedID = -1;
		}
	}

	/*
	 * Set Row Enable
	 */
	private void setRowEnable(int row, boolean value, boolean order) {
		if (row <= flexTable.getRowCount() - 1 && row > 0) {
			CheckBox orderCheckBox = (CheckBox) flexTable.getWidget(row, 0);
			orderCheckBox.setValue(value);
			orderCheckBox.setEnabled(order);
			TextBox varnameTextBox = (TextBox) flexTable.getWidget(row, 1);
			varnameTextBox.setReadOnly(!value);
			TextBox desTextBox = (TextBox) flexTable.getWidget(row, 2);
			desTextBox.setReadOnly(!value);
		}
	}

	private void setRowEnable(int row, boolean value) {
		setRowEnable(row, value, true);
	}

	/*
	 * Get Order CheckBox
	 */
	private CheckBox OrderCheckBox(int row, boolean value, boolean enable) {
		final CheckBox cb = new CheckBox();
		cb.setValue(value);
		cb.setEnabled(enable);
		return cb;
	}

	/*************************************************************************/
	/*
	 * Init
	 */

	private void initTableFirst() {
		flexTable.removeAllRows();
		/*
		 * Tên các cột
		 */
		int i = 0;
		for (final String columnName : listStringColumn) {
			flexTable.setHTML(0, i, "<center><b>" + columnName
					+ "</b></center>");
			i++;
		}
	}

	/*
	 * Add Row with Wiget
	 */
	private int addRow(Widget varnameTextbox, Widget desTextbox) {
		int row = flexTable.getRowCount();
		CheckBox sttCheckbox = OrderCheckBox(row, false, true);
		flexTable.setWidget(row, 0, sttCheckbox);
		flexTable.setWidget(row, 1, varnameTextbox);
		flexTable.setWidget(row, 2, desTextbox);
		setRowEnable(row, false);
		return row;
	}

	/*
	 * Add Row with data
	 */
	private int addRow(String name, String des) {
		int row = flexTable.getRowCount();

		CheckBox sttCheckbox = OrderCheckBox(row, false, true);
		flexTable.setWidget(row, 0, sttCheckbox);

		TextBox nameTextBox = new TextBox();
		nameTextBox.setValue(name);
		flexTable.setWidget(row, 1, nameTextBox);

		TextBox desTextBox = new TextBox();
		desTextBox.setValue(des);
		flexTable.setWidget(row, 2, desTextBox);

		setRowEnable(row, false);

		return row;
	}

	/*
	 * Add Row Empty
	 */
	private int addRow() {
		int row = addRow(new TextBox(), new TextBox());
		setRowEnable(row, false);
		return row;
	}

	/*
	 * Remove selected Row
	 */
	private void removeRow() {
		if (rowSelectedID > 0 && rowSelectedID < flexTable.getRowCount()
				&& rowSelectedID != rowEditingID) {
			flexTable.removeRow(rowSelectedID);
			int remvIndex = Helper.getIndexByRow(rowSelectedID, listRow.size());
			if (remvIndex != -1) {
				listRow.remove(remvIndex);
			}
			rowSelectedID = -1;
		} else
			Window.alert("Chọn hàng cần xóa!");
	}

	/*
	 * Update all rows
	 */
	private void updateRow() {
		for (int index = 0; index < listRow.size() ; index++) {
			int row = Helper.getRowByIndex(index, flexTable.getRowCount());

			TextBox varnameTextBox = (TextBox) flexTable.getWidget(row, 1);
			TextBox desTextBox = (TextBox) flexTable.getWidget(row, 2);
			listRow.get(index).setVarName(varnameTextBox.getValue());
			listRow.get(index).setPropertyPath(desTextBox.getValue());
		}
		
		if (flexTable.getRowCount() - 1 > listRow.size()) {
			for (int row = listRow.size()+1; row < flexTable
					.getRowCount(); row++) {
				TextBox varnameTextBox = (TextBox) flexTable.getWidget(row, 1);
				TextBox desTextBox = (TextBox) flexTable.getWidget(row, 2);
				RuleParamDTO o = new RuleParamDTO(
						KeyFactory.keyToString(this.currentRuleSetDTO.getId()), 
						null, Helper.PARAMTYPE.RULE.toString(), varnameTextBox.getValue(), null, desTextBox.getValue(), -1);
				listRow.add(o);
			}
		}
	}

	/*
	 * Event
	 */

	@UiHandler("btAdd")
	void onBtAddClick(ClickEvent event) {
		addRow();
	}

	@UiHandler("btDel")
	void onBtDelClick(ClickEvent event) {
		removeRow();
	}

	@UiHandler("btUpdate")
	void onBtUpdateClick(ClickEvent event) {
		updateRow();
	}

	/***************************************************************/

	/*
	 * Overide Display
	 */
	@Override
	public Button getUpdateButton() {
		return btUpdate;
	}

	@Override
	public ArrayList<RuleParamDTO> getListRow() {
		return (ArrayList<RuleParamDTO>) listRow;
	}

	@Override
	public boolean setListRow(List<RuleParamDTO> listRow) {
		this.listRow = listRow;
		return true;
	}

	@Override
	public void render() {
		rowSelectedID = -1;
		rowEditingID = -1;
		initTableFirst();
		for (final RuleParamDTO o : this.listRow) {
			addRow(o.getName(), o.getPropertyPath());
		}
	}

	@Override
	public Widget asWidget() {
		return this;
	}

}
